package org.example.spring_blog.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.example.spring_blog.enums.ResultCodeEnum;
import org.example.spring_blog.model.Result;
import org.example.spring_blog.model.UserInfo;
import org.example.spring_blog.service.UserInfoService;
import org.example.spring_blog.util.SecurityUtils;
import org.example.spring_blog.util.jwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserInfoService userInfoService;

    Map<String,Object> claims=new HashMap<>();
    @RequestMapping("/login")
    public Result login(String userName, String password){
        log.info("用户登录, userName: {}", userName);
        Assert.hasLength(userName, "用户名不能为空");
        Assert.hasLength(password, "密码不能为空");
        //验证账号密码是否正确
        UserInfo userInfo = userInfoService.getByName(userName);
        if (userInfo==null || userInfo.getId()==null){
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "用户不存在");
        }
        if (!SecurityUtils.verify(password, userInfo.getPassword())){
            log.error("密码验证失败");
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
        }
//        if (!password.equals(userInfo.getPassword())){
//            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
//        }
        //账号密码正确的逻辑
        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id", userInfo.getId());
        cliams.put("name", userInfo.getUserName());

        String jwt = jwtUtils.getJwt(cliams);
        return Result.success(jwt);

    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String jwt=request.getHeader("user_token_header");
        Assert.notNull(jwt,"未登录");
        Integer id = jwtUtils.getUserIdFromToken(jwt);
        UserInfo userInfo = userInfoService.getUserInfo(id);
        return userInfo;
    }

    @RequestMapping("/gerAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        Assert.notNull(blogId,"博客ID不能为空");
        return userInfoService.getAuthorInfo(blogId);
    }
}
